package site.addzero.repl

import kotlinx.coroutines.runBlocking
import org.koin.core.annotation.Single
import site.addzero.app.AdvancedRepl
import site.addzero.app.ParamDef
import site.addzero.cli.platform.PlatformStrategy
import site.addzero.cli.platform.PlatformType

/**
 * InitLazyVimRepl的REPL包装类，实现AdvancedRepl接口
 * 专门用于初始化LazyVim配置
 */
@Single
class InitLazyVimRepl(private val platformStrategy: PlatformStrategy) : AdvancedRepl<Unit, String> {
    override val command: String = "init-lazyvim"
    override val description: String = "初始化LazyVim配置（支持Windows、Linux和MacOS）"
    override val paramDefs: List<ParamDef> = listOf()

    override fun eval(params: Unit): String = runBlocking {
        println("正在初始化LazyVim配置...")

        val platformType = platformStrategy.getPlatformType()
        val result = when (platformType) {
            PlatformType.WINDOWS -> initLazyVimOnWindows()
            PlatformType.LINUX, PlatformType.MACOS -> initLazyVimOnUnix()
            PlatformType.UNKNOWN -> {
                System.err.println("不支持的操作系统")
                return@runBlocking "LazyVim初始化失败: 不支持的操作系统"
            }
        }

        if (result) {
            println("LazyVim初始化成功完成!")
            println("请运行 :LazyHealth 检查配置是否正确加载")
            return@runBlocking "LazyVim初始化成功"
        } else {
            System.err.println("LazyVim初始化失败")
            return@runBlocking "LazyVim初始化失败"
        }
    }

    private fun initLazyVimOnWindows(): Boolean {
        println("检测到Windows系统，执行Windows安装步骤...")

        // 备份现有配置
        val backupCommands = listOf(
            "Move-Item \$env:LOCALAPPDATA\\nvim \$env:LOCALAPPDATA\\nvim.bak -ErrorAction SilentlyContinue",
            "Move-Item \$env:LOCALAPPDATA\\nvim-data \$env:LOCALAPPDATA\\nvim-data.bak -ErrorAction SilentlyContinue"
        )

        backupCommands.forEach { command ->
            val result = platformStrategy.executeCommand(command)
            if (!result.isSuccess() && !result.output.contains("because it does not exist")) {
                System.err.println("备份失败: ${result.error}")
                return false
            }
        }

        // 克隆starter配置
        val cloneResult = platformStrategy.executeCommand(
            "git clone https://github.com/LazyVim/starter \$env:LOCALAPPDATA\\nvim"
        )
        if (!cloneResult.isSuccess()) {
            System.err.println("克隆配置失败: ${cloneResult.error}")
            return false
        }

        // 删除.git文件夹
        val removeGitResult = platformStrategy.executeCommand(
            "Remove-Item \$env:LOCALAPPDATA\\nvim\\.git -Recurse -Force -ErrorAction SilentlyContinue"
        )
        if (!removeGitResult.isSuccess() && !removeGitResult.output.contains("because it does not exist")) {
            System.err.println("删除.git文件夹失败: ${removeGitResult.error}")
            return false
        }

        return true
    }

    private fun initLazyVimOnUnix(): Boolean {
        println("检测到Unix系统（Linux/MacOS），执行Unix安装步骤...")

        // 备份现有配置
        val backupCommands = listOf(
            "mv ~/.config/nvim{,.bak} 2>/dev/null || true",
            "mv ~/.local/share/nvim{,.bak} 2>/dev/null || true",
            "mv ~/.local/state/nvim{,.bak} 2>/dev/null || true",
            "mv ~/.cache/nvim{,.bak} 2>/dev/null || true"
        )

        backupCommands.forEach { command ->
            val result = platformStrategy.executeCommand(command)
            if (!result.isSuccess() && !result.output.contains("No such file or directory")) {
                System.err.println("备份失败: ${result.error}")
                return false
            }
        }

        // 克隆starter配置
        val cloneResult = platformStrategy.executeCommand(
            "git clone https://github.com/LazyVim/starter ~/.config/nvim"
        )
        if (!cloneResult.isSuccess()) {
            System.err.println("克隆配置失败: ${cloneResult.error}")
            return false
        }

        // 删除.git文件夹
        val removeGitResult = platformStrategy.executeCommand(
            "rm -rf ~/.config/nvim/.git"
        )
        if (!removeGitResult.isSuccess()) {
            System.err.println("删除.git文件夹失败: ${removeGitResult.error}")
            return false
        }

        return true
    }

//    override fun createParams(values: List<Any?>) {
//        return
//    }
}
